

package org.koyabr.webx.demo.danmaku.web.user.module.action;

import static com.alibaba.citrus.util.CollectionUtil.*;
import static org.koyabr.webx.demo.danmaku.web.common.DanmakuConstant.*;

import java.util.Map;
import javax.servlet.http.HttpSession;

import com.alibaba.citrus.service.form.CustomErrors;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormField;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import org.koyabr.webx.demo.danmaku.biz.DuplicatedUserException;
import org.koyabr.webx.demo.danmaku.biz.UserManager;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.User;
import org.koyabr.webx.demo.danmaku.web.common.DanmakuUser;
import org.springframework.beans.factory.annotation.Autowired;

public class RegisterAction {
    @Autowired
    private UserManager userManager;

    public void doRegister(@FormGroup("register") User user,
                           @FormField(name = "registerError", group = "register") CustomErrors err,
                           HttpSession session, Navigator nav) throws Exception {
        try {
            userManager.register(user);

            // 在session中创建danmakuUser对象
            DanmakuUser danmakuUser = (DanmakuUser) session.getAttribute(DANMAKU_USER_SESSION_KEY);

            if (danmakuUser == null || danmakuUser.hasLoggedIn()) {
                danmakuUser = new DanmakuUser();
            }

            danmakuUser.upgrade(user.getUsername());

            session.setAttribute(DANMAKU_USER_SESSION_KEY, danmakuUser);

            // 跳转到个人资料编辑页面
            nav.redirectTo(DANMAKU_PROFILE_EDIT_LINK);
        } catch (DuplicatedUserException e) {
            Map<String, Object> params = createHashMap();
            params.put("username", user.getUsername());

            err.setMessage("duplicatedUsername", params);
        }
    }


}
